package com.audaque.springboot.foshanupload.db.util.page;


import com.audaque.springboot.foshanupload.core.inface.PageFunction;
import com.audaque.springboot.foshanupload.core.model.qo.page.Page;


import java.util.ArrayList;
import java.util.List;

/**
 * 分页工具类
 *
 * @author wuwei
 */
public class PageUtil {

    public static <T> Page<T> execute(Page<T> page, PageFunction<T> handler) {
        if (page.getLimit() == Integer.MAX_VALUE) {
            List<T> list = handler.query();
            page.setTotal(list.size());
            page.setRecords(list);
            return page;
        }

        if (page.getLimit() <= 0) {
            page.setTotal(handler.count());
            page.setRecords(new ArrayList<T>());
            return page;
        }

        if (!page.isCalculateCount()) {
            List<T> list = handler.query();
            page.setRecords(list);
            if (list.size() == page.getLimit()) {
                page.setTotal(-1);
            } else {
                page.setTotal(list.size());
            }
            return page;
        }

        int count = handler.count();
        page.setTotal(count);
        if (count == 0) {
            page.setRecords(new ArrayList<T>());
            return page;
        }

        // 根据总条数，调整开始下标，设置成最后一页中第一条数据的下标
        if (page.getOffset() >= count) {
            if (count % page.getLimit() == 0) {
                page.setOffset(count - page.getLimit());
            } else {
                page.setOffset(count / page.getLimit() * page.getLimit());
            }
        }

        List<T> list = handler.query();
        page.setRecords(list);
        return page;
    }


}
